package syn;

/**
 * @author mubei
 * @date 2021/11/20
 * @description
 */
public class BuyTicket implements Runnable{


    private int ticketNum = 10;
    boolean flag = true;//外部ting

    @Override
    public void run() {
        while(flag){
            buy();
        }
    }

    // synchronized  锁的是this
    private synchronized void buy(){
        //判断是否有票
        if(ticketNum<=0){
            flag = false;
            return ;
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"ah").start();
        new Thread(buyTicket,"mubei").start();
        new Thread(buyTicket,"zl").start();
    }
}
